<template>
  <view class="device-control-container">
    <view class="device-header">
      <view class="device-info">
        <text class="device-name">{{ currentDevice?.name }}</text>
        <text class="device-location">{{ currentDevice?.location }}</text>
      </view>
      
      <view class="device-status">
        <u-tag 
          :text="getStatusText(currentDevice?.status)" 
          :type="getStatusType(currentDevice?.status)"
          size="mini"
        />
      </view>
    </view>
    
    <view class="control-panel">
      <view class="timer">
        <u-count-down 
          :time="countdownTime" 
          format="mm:ss" 
          :show-days="false"
          :autoStart="isRunning"
          ref="countdownRef"
        >
          <template #default="{ timeData }">
            <view class="countdown-display">
              <text class="time-text">{{ `${timeData.minutes}:${timeData.seconds}` }}</text>
            </view>
          </template>
        </u-count-down>
      </view>
      
      <view class="control-buttons">
        <u-button 
          v-if="!isRunning" 
          type="primary" 
          @click="startDevice"
          :disabled="currentDevice?.status !== 'available'"
        >
          启动洗车
        </u-button>
        
        <u-button 
          v-else 
          type="error" 
          @click="stopDevice"
        >
          停止洗车
        </u-button>
        
        <u-button 
          type="default" 
          @click="goBack"
        >
          返回
        </u-button>
      </view>
    </view>
    
    <view class="device-functions">
      <view class="function-title">设备功能</view>
      
      <view class="function-grid">
        <view 
          class="function-item" 
          v-for="func in functions" 
          :key="func.id"
          :class="{ active: func.active }"
          @click="toggleFunction(func)"
        >
          <u-icon :name="func.icon" size="40" :color="func.active ? '#007aff' : '#999'"></u-icon>
          <text class="function-name">{{ func.name }}</text>
        </view>
      </view>
    </view>
    
    <view class="device-tips">
      <view class="tip-title">使用提示</view>
      <view class="tip-content">
        <text>1. 请确保车辆停放在正确位置</text>
        <text>2. 洗车过程中请勿下车</text>
        <text>3. 如遇紧急情况，请立即按下停止按钮</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useDeviceStore } from '@/store/device'
import { startDevice as apiStartDevice, stopDevice as apiStopDevice } from '@/api/device'

interface DeviceFunction {
  id: string
  name: string
  icon: string
  active: boolean
}

// 设备store
const deviceStore = useDeviceStore()

// 倒计时相关
const countdownRef = ref<any>(null)
const countdownTime = ref(600000) // 10分钟
const isRunning = ref(false)

// 设备功能
const functions = ref<DeviceFunction[]>([
  { id: 'water', name: '清水', icon: 'water', active: true },
  { id: 'foam', name: '泡沫', icon: 'gift', active: false },
  { id: 'wax', name: '蜡水', icon: 'star', active: false },
  { id: 'drying', name: '风干', icon: 'file-text', active: false }
])

// 当前设备
const currentDevice = computed(() => deviceStore.getCurrentDevice)

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    available: '空闲',
    occupied: '占用',
    maintenance: '维护',
    offline: '离线'
  }
  
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    available: 'success',
    occupied: 'warning',
    maintenance: 'error',
    offline: 'info'
  }
  
  return typeMap[status] || 'info'
}

// 切换功能
const toggleFunction = (func: DeviceFunction) => {
  if (isRunning.value) {
    uni.showToast({ title: '设备运行中，无法切换功能', icon: 'none' })
    return
  }
  
  func.active = !func.active
}

// 启动设备
const startDevice = async () => {
  if (!currentDevice.value) {
    uni.showToast({ title: '设备信息异常', icon: 'none' })
    return
  }
  
  uni.showLoading({ title: '启动中...' })
  
  try {
    const res = await apiStartDevice(currentDevice.value.id)
    
    if (res.code === 200) {
      isRunning.value = true
      uni.showToast({ title: '设备启动成功', icon: 'success' })
      
      // 更新设备状态
      deviceStore.updateDeviceStatus(currentDevice.value.id, 'occupied')
    } else {
      uni.showToast({ title: res.message, icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: '启动失败，请重试', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 停止设备
const stopDevice = async () => {
  if (!currentDevice.value) {
    uni.showToast({ title: '设备信息异常', icon: 'none' })
    return
  }
  
  uni.showModal({
    title: '确认停止',
    content: '确定要停止洗车吗？',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '停止中...' })
        
        try {
          const res = await apiStopDevice(currentDevice.value!.id)
          
          if (res.code === 200) {
            isRunning.value = false
            uni.showToast({ title: '设备已停止', icon: 'success' })
            
            // 更新设备状态
            deviceStore.updateDeviceStatus(currentDevice.value!.id, 'available')
          } else {
            uni.showToast({ title: res.message, icon: 'none' })
          }
        } catch (error) {
          uni.showToast({ title: '停止失败，请重试', icon: 'none' })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面参数
const deviceId = ref('')

onLoad((options) => {
  if (options?.id) {
    deviceId.value = options.id
    // 根据设备ID获取设备详情
    const device = deviceStore.getDevices.find(d => d.id === options.id)
    if (device) {
      deviceStore.setCurrentDevice(device)
    }
  }
})

onShow(() => {
  // 页面显示时的逻辑
})

onUnmounted(() => {
  // 页面卸载时的逻辑
  if (isRunning.value) {
    isRunning.value = false
  }
})
</script>

<style lang="scss" scoped>
.device-control-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.device-header {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.device-info {
  display: flex;
  flex-direction: column;
}

.device-name {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.device-location {
  font-size: 28rpx;
  color: #999;
}

.control-panel {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  text-align: center;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.timer {
  margin-bottom: 40rpx;
}

.countdown-display {
  .time-text {
    font-size: 72rpx;
    font-weight: bold;
    color: #333;
  }
}

.control-buttons {
  display: flex;
  gap: 20rpx;
  
  .u-button {
    flex: 1;
  }
}

.device-functions {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.function-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.function-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  border-radius: 10rpx;
  background-color: #f5f5f5;
  
  &.active {
    background-color: #e6f2ff;
  }
  
  .function-name {
    font-size: 24rpx;
    color: #666;
    margin-top: 10rpx;
  }
}

.device-tips {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.tip-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.tip-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  
  text {
    font-size: 28rpx;
    color: #666;
    padding-left: 20rpx;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 10rpx;
      height: 10rpx;
      border-radius: 50%;
      background-color: #007aff;
    }
  }
}
</style>